# -*- mode: python -*-
###
#
# (c) 2000-2007 Wijnand Modderman <wijnand at tehmaze dot com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###

# system imports

# DDB imports
from ddb.log import log
from ddb.transport import ITransport, ITransportProtocol

# Twisted imports
from twisted.internet import protocol, reactor
from twisted.words.protocols import oscar

class oscarProtocol(ITransportProtocol, oscar.OscarConnection):
    """IRC protocol skell."""

    #
    # Generic connection-related
    #
    def connectionMade(self):
        if self.factory.config.has_key('identity'):
            self.nickname = self.factory.config['identity'][0]
        if self.factory.config.has_key('realname'):
            self.realname = self.factory.config['realname'][0]
        if self.factory.config.has_key('username'):
            self.username = self.factory.config['username'][0]
        ITransportProtocol.connectionMade(self)
        irc.IRCClient.connectionMade(self)

    def connectionLost(self, reason=''):
        ITransportProtocol.connectionLost(self, reason)
        irc.IRCClient.connectionLost(self, reason)

    def lineReceived(self, line):                                                                                                                                                     
        log.msg('<<< %s' % line, debug=True)                                                                                                                                          
        irc.IRCClient.lineReceived(self, line)     

    #
    # Raw low-level IRC protocol handling
    #

    def irc_JOIN(self, prefix, params):
        nick   = prefix.split('!')[0]
        target = params[-1]
        if nick == self.nickname:
            self.joined(target)
        else:
            self.userJoined(prefix, target)

    def irc_PART(self, prefix, params):
        nick   = prefix.split('!')[0]
        target = params[0]
        if nick == self.nickname:
            self.left(target)
        else:
            self.userLeft(nick, target)

    def irc_RPL_WHOREPLY(self, prefix, params):
        _, target, ident, host, server, nickname, status, realname = params
        mask = '%s!%s@%s' % (nickname, ident, host)
        self.userJoined(mask, target)

    #
    # Status updates about myself
    #

    def signedOn(self):
        """Logged in successfully."""
        ITransportProtocol.signedOn(self)
        print self.factory.config
        if self.factory.config.has_key('conference'):
            for conference in self.factory.config['conference']:
                if ' ' in conference:
                    conference, key = conference.split(' ', 1)
                else:
                    key = None
                self.join(conference, key)

    def joined(self, target):
        ITransportProtocol.openedConference(self, target)
        self.sendLine('WHO %s' % target)

    def parted(self, target):
        self.users.removeConference(target)
        ITransportProtocol.closedConference(self, target)
 
    #
    # Status updates about others
    #

    def userJoined(self, mask, target):
        nickname = mask.split('!')[0]
        ITransportProtocol.joinedConference(self, nickname, mask, target)

    def userLeft(self, mask, target):
        nickname = mask.split('!')[0]
        ITransportProtocol.partedConference(self, nickname, mask, target)

class OscarFactory(protocol.ClientFactory):
    def __init__(self, config):
        self.config = config

    def startedConnecting(self, connector):
        logging.info('Started to connect to oscar')
        
class transport(ITransport):
    """IRC Transport base class."""
    protocol = oscarProtocol
    factory  = oscarFactory

    def __init__(self, config):
        ITransport.__init__(self, config)
        log.msg('starting %s' % str(self.__class__))
        print config
        # 2006/12/22 15:42 CET [-] {'conference': ['#ddb', '#test', '&test'], 'host': ['irc.freecode.nl'], 'identity': ['BORK_DDB'], 'transport': ['irc'], 'port': ['6667']}
        #reactor.connectTCP('irc.freecode.nl', 6667, self.server)
        try:
            serverHost = config['host'][0]
        except KeyError, e:
            log.msg('Could not start transport, missing configuration option "%s"' % str(e))
            return
        self.server = self.factory(config)
        reactor.connectTCP(serverHost, serverPort, self.server)

    def start(self):
        self.run = True

    def stop(self):
        self.run = False

# vim:ts=4:sw=4:et:
